import * as TYPES from './actionTypes'
import * as fetch from '../utils/fetch';
import * as storage from '../utils/storage';
import * as NavigatorService from '../utils/NavigatorService';
import o from '../components/o';
import Toast from 'react-native-root-toast'
import CODE from '../utils/codeConfig'
import Constant from '../utils/Constant'
import { StackActions, NavigationActions } from 'react-navigation';
const PERMISSION = Constant.PERMISSION
export function showToast(params) {
    const { msg, position, duration } = params
    Toast.show(msg, {
        position: position || Toast.positions.CENTER,
        duration: duration || Toast.durations.LONG,
    })
}

//显示登录
export function login(params) {
    return (dispatch) => {
        dispatch({ 'type': TYPES.LOGIN_ING });
        fetch.request('/rest/wxauth/login', 'get', params).then((res) => {
            const { statuCode } = res.code
            if (statuCode == CODE.SUCCESS) {
                storage.save("openid", res.openid)
                let params = {
                    openid: res.openid
                }
                dispatch(loginSuccess({ openid: res.openid }));
                reLaunch()
            } else if (statuCode == CODE.UNREGISTERED) {
                dispatch({ type: TYPES.LOGIN_FAIL });
                let params = { msg: "暂未注册或未绑定手机号,无法登录" }
                showToast(params)
            } else if (statuCode == CODE.VERIFICATION_CODE_TIME_OUT) {
                let params = { msg: "验证码超时" }
                showToast(params)
                dispatch({ type: TYPES.LOGIN_FAIL });
            } else if (statuCode == CODE.VERIFICATION_CODE_NOT_EXISTED || statuCode == CODE.VERIFICATION_CODE_OR_PHONE_NUMBER_WORNG) {
                dispatch({ type: TYPES.LOGIN_FAIL });
                let params = { msg: "验证码错误" }
                showToast(params)
            } else {
                let params = { msg: "登录异常" }
                showToast(params)
                dispatch({ type: TYPES.LOGIN_FAIL });
            }
        }).catch((res) => {
            let params = { msg: "登录异常" }
            showToast(params)
            dispatch({ type: TYPES.LOGIN_FAIL });
        })
    }
}
export function loginSuccess(params) {
    return dispatch => {
        dispatch({ type: TYPES.LOGIN_SUCCESS, openid: params.openid });
    }

}

export function goLogin() {
    global.storage.save({ key: "page", data: "dddd" })
    global.storage.load({
        key: "page"
    }).then(res => { console.log(res) })
    return (dispatch) => {
        dispatch({ 'type': TYPES.GO_LOGIN })
    }
}

export function getToken(params) {
    // fetch.request('',)
    return (dispatch) => {
        dispatch({ type: TYPES.GETTOKEN_ING })
        fetch.request('/rest/wxauth/user', 'get', params).then(res => {
            const { statuCode } = res.code;
            if (statuCode == CODE.SUCCESS) {
                let params_here = {
                    roleList: res.roles,
                    token: res.token,
                    openid: res.openid
                }
                dispatch(getUserInfo(params_here))
            } else {
                showToast({ msg: "获取用户验证异常" })
                // dispatch({ type: TYPES.LOGIN_FAIL });
            }
        }).catch(e => {
            showToast({ msg: "获取用户验证异常" })
            // dispatch({ type: TYPES.LOGIN_FAIL });
        })
    }

}

export function getUserInfo(paramsP) {
    //如果用token取信息失败的话 说明token失效 需要重新登录获取新detoken 
    return (dispatch) => {

        const { openid, roleList, token } = paramsP
        let params = {
            select: 'openid,Nickname,Mobile,UserState,UserId,TenantId',
            filter: `openid eq '${openid}' and UserState eq 1`,
            expand: 'user_file($select=Url)',
            api: `erp_user?token=${token}`
        }

        o(params.api).select(params.select).filter(params.filter).expand(params.expand).get().then(oHandler => {

            const data = oHandler.data
            let paramsC = Object.assign(paramsP, { userInfo: data[0] })
            if (roleList && roleList[0].RoleName == '管理员') {
                dispatch(getTokenSuccess(paramsC))
            } else {
                dispatch(getRolePemiision(paramsC))
            }
        }).catch(e => {
            // dispatch({ type: TYPES.GETTOKEN_FAIL })
            console.log(e)
            // showToast({ msg: "获取用户信息失败" })
        })
    }
}

export function getRolePemiision(paramsP) {
    return (dispatch) => {
        let filter = '';
        const { roleList, token } = paramsP;
        for (let i = 0; i < roleList.length; i++) {
            if (filter) {
                filter = filter + ' or RoleId eq ' + Number(roleList[i].RoleID)
            } else {
                filter = 'RoleId eq ' + roleList[i].RoleID
            }
        }
        let params = {
            filter: filter,
            api: `erp_role_permission?token=${token}`,
        }

        o(params.api).filter(params.filter).get().then(oHandler => {

            const res = oHandler.data;
            if (res && res.length > 0) {
                dispatch(getPermission(paramsP, res));
            }
        }).catch(e => {
            showToast({ msg: "获取用户角色权限失败" });
            dispatch({ type: TYPES.GETTOKEN_FAIL })
        })
    }
}

export function getPermission(paramsP, rolePermission) {
    return (dispatch) => {

        const { token } = paramsP;
        let filter = '';
        for (let i = 0; i < rolePermission.length; i++) {
            if (filter) {
                filter = filter + ' or permission_id eq ' + rolePermission[i].PermissionId
            } else {
                filter = 'permission_id eq ' + rolePermission[i].PermissionId
            }
        }
        let params = {
            filter: filter,
            select: 'permission_id,PermissionName',
            api: `erp_permission?token=${token}`
        }
        o(params.api).select(params.select).filter(params.filter).get().then(oHandler => {
            const res = oHandler.data;
            let paramsC = Object.assign(paramsP, { permissionList: res })
            dispatch(getTokenSuccess(paramsC))

        }).catch(e => {
            showToast({ msg: "获取用户权限失败" })
        })
    }
}
export function getTokenSuccess(paramsP) {
    return (dispatch) => {
        let permission = {
            PURCHASE: false,
            SALE: false,
            CHECKS: false,
        };

        const { roleList, permissionList, userInfo } = paramsP;
        if (roleList && roleList[0] && roleList[0].RoleName != '管理员') {
            for (let i = 0; i < permissionList.length; i++) {
                switch (permissionList[i].PermissionName) {
                    case PERMISSION.PURCHASE:
                        permission.PURCHASE = true;
                        break;
                    case PERMISSION.SALE:
                        permission.SALE = true;
                        break;
                    case PERMISSION.CHECKS:
                        permission.CHECKS = true;
                        break;
                    default:
                        break
                }
            }

        } else {
            permission = {
                PURCHASE: true,
                SALE: true,
                CHECKS: true,
            }
        }
        dispatch({ type: TYPES.GETTOKEN_SUCCESS, ...paramsP, userId: userInfo.UserId, TenantId: userInfo.TenantId, permission: permission })
        reLaunch()
    }
}

export function reLaunch() {
    NavigatorService.reset("Index")
}